/* eslint-disable no-param-reassign */
import {
  IRoutePathNode,
  route2routePath,
  routePath2string,
  useNamespace,
} from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType } from 'vue';
import { PanelItemController } from '@ibiz-template/runtime';
import { IPanelRawItem } from '@ibiz/model-core';
import { useRouter } from 'vue-router';
import './head-sculpture.scss';

export const HeaderSculptures = defineComponent({
  name: 'HeaderSculptures',
  props: {
    modelData: {
      type: Object as PropType<IPanelRawItem>,
      required: true,
    },
    controller: {
      type: PanelItemController,
      required: true,
    },
  },
  setup(props) {
    const c = props.controller!;
    const ns = useNamespace('panel-item');
    const router = useRouter();
    const _name: string = props.controller.model.id || '';

    const itemType = props.controller.model.itemType;

    const items = computed(() => {
      if (props.controller.data) {
        if (itemType === 'CONTAINER') {
          return [props.controller.data];
        }
        const _value = props.controller.data[_name];
        if (_value && Array.isArray(_value)) {
          return _value;
        }
      }
      return [];
    });

    const classArr = computed(() => {
      const { id } = props.modelData;
      const result: Array<string | false> = [ns.b(), ns.m(id)];
      result.push(...props.controller.containerClass);
      return result;
    });

    const handleSelect = (item: IData) => {
      const { data, evt } = item;
      evt.stopPropagation();
      if (itemType === 'CONTAINER') {
        const route = router.currentRoute.value;
        const routePath = route2routePath(route);
        routePath.pathNodes.forEach(
          (pathNode: IRoutePathNode, index: number) => {
            if (index === 1) {
              pathNode.srfnav = `root:node@${data.srfkey}`;
            } else if (index === 2) {
              pathNode.srfnav = `${data.srfkey}`;
              pathNode.context!.ggfxzt = `${data.srfkey}`;
            } else if (index === 3) {
              pathNode.context!.ggfxzt = `${data.srfkey}`;
            }
          },
        );
        const path = routePath2string(routePath);
        if (route.fullPath !== path) {
          console.warn(routePath);
          router.push(path);
        }
      }
    };

    return {
      items,
      c,
      ns,
      classArr,
      itemType,
      handleSelect,
    };
  },
  render() {
    return (
      <div class={this.classArr}>
        <iBizAvatar
          items={this.items}
          showName={this.itemType === 'CONTAINER'}
          onSelectChange={(item: IData) => this.handleSelect(item)}
        ></iBizAvatar>
      </div>
    );
  },
});
